package com.shop.cloud.mall.admin.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.common.security.annotation.Inside;
import com.shop.cloud.common.security.util.SecurityUtils;
import com.shop.cloud.mall.admin.service.*;
import com.shop.cloud.mall.common.constant.MallConstants;
import com.shop.cloud.mall.common.entity.*;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * spu商品
 *
 * @author
 * @date 2019-08-12 16:25:10
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/goodsspu")
@Tag(description = "goodsspu", name = "spu商品管理")
public class GoodsSpuController {

    private final GoodsSpuService goodsSpuService;
	private final FreightTemplatService freightTemplatService;
	private final BargainInfoService bargainInfoService;
	private final GrouponInfoService grouponInfoService;
	private final SeckillInfoService seckillInfoService;
	private final SupplierGoodsSpuService supplierGoodsSpuService;

    /**
    * 分页查询
    * @param page 分页对象
    * @param goodsSpu spu商品
    * @return
    */
	@Operation(summary = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@ato.hasAuthority('mall:goodsspu:index')")
    public R getPage(Page page, GoodsSpu goodsSpu) {
		return R.ok(goodsSpuService.page1(page, goodsSpu));
    }

	/**
	 * list查询
	 * @param goodsSpu
	 * @return
	 */
	@Operation(summary = "list查询")
	@GetMapping("/list")
	public List<GoodsSpu> getList(GoodsSpu goodsSpu) {
		return goodsSpuService.list(Wrappers.query(goodsSpu).lambda()
				.select(GoodsSpu::getId,
						GoodsSpu::getName,
						GoodsSpu::getShopId)
		);
	}

	/**
	 * 查询数量
	 * @param goodsSpu
	 * @return
	 */
	@Operation(summary = "查询数量")
	@GetMapping("/count")
	@PreAuthorize("@ato.hasAuthority('mall:goodsspu:count')")
	public R getCount(GoodsSpu goodsSpu) {
		return R.ok(goodsSpuService.count(Wrappers.query(goodsSpu)));
	}

    /**
    * 通过id查询spu商品
    * @param id
    * @return R
    */
	@Operation(summary = "通过id查询spu商品")
    @GetMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('mall:goodsspu:get')")
    public R getById(@PathVariable("id") String id){
        return R.ok(goodsSpuService.getById1(id));
    }

    /**
    * 新增spu商品
    * @param goodsSpu spu商品
    * @return R
    */
	@Operation(summary = "新增spu商品")
    @SysLog("新增spu商品")
    @PostMapping
    @PreAuthorize("@ato.hasAuthority('mall:goodsspu:add')")
    public R save(@RequestBody GoodsSpu goodsSpu){
		goodsSpu.setVerifyStatus(MallConstants.GOODS_STATUS_0);
//		if(MallConstants.FREIGHT_TYPE_2.equals(goodsSpu.getFreightType())){
//			FreightTemplat freightTemplat = freightTemplatService.getById(goodsSpu.getFreightTemplatId());
//			if(!goodsSpu.getShopId().equals(freightTemplat.getShopId())){
//				return R.failed("请选择商品所属店铺下的运费模板");
//			}
//		}
		try {
			return R.ok(goodsSpuService.save1(goodsSpu));
		}catch (DuplicateKeyException e){
			if(e.getMessage().contains("uk_code")){
				return R.failed("商品编码已存在");
			}else{
				return R.failed(e.getMessage());
			}
		}
    }

	/**
	 * 批量新增spu商品
	 * @param listGoodsSpu spu商品集合
	 * @return R
	 */
	@Operation(summary = "批量新增spu商品")
	@SysLog("批量新增spu商品")
	@PostMapping("/batch")
	@PreAuthorize("@ato.hasAuthority('mall:goodsspu:add')")
	public R saveBatch(@RequestBody List<GoodsSpu> listGoodsSpu){
		try {
			return goodsSpuService.saveBatch1(listGoodsSpu);
		}catch (DuplicateKeyException e){
			if(e.getMessage().contains("uk_code")){
				return R.failed("商品编码已存在"+e.getMessage());
			}else{
				return R.failed(e.getMessage());
			}
		}
	}

    /**
    * 修改spu商品
    * @param goodsSpu spu商品
    * @return R
    */
	@Operation(summary = "修改spu商品")
    @SysLog("修改spu商品")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('mall:goodsspu:edit')")
    public R updateById(@RequestBody GoodsSpu goodsSpu){
		goodsSpu.setVerifyStatus(MallConstants.GOODS_STATUS_0);
//		if(MallConstants.FREIGHT_TYPE_2.equals(goodsSpu.getFreightType())){
//			FreightTemplat freightTemplat = freightTemplatService.getById(goodsSpu.getFreightTemplatId());
//			if(!goodsSpu.getShopId().equals(freightTemplat.getShopId())){
//				return R.failed("请选择商品所属店铺下的运费模板");
//			}
//		}
		try {
			return R.ok(goodsSpuService.updateById1(goodsSpu));
		}catch (DuplicateKeyException e){
			if(e.getMessage().contains("uk_code")){
				return R.failed("商品编码已存在");
			}else{
				return R.failed(e.getMessage());
			}
		}
    }

	/**
	 * 商品上下架操作
	 * @param shelf
	 * @param ids
	 * @return R
	 */
	@Operation(summary = "商品上下架操作")
	@SysLog("商品上下架操作")
	@PutMapping("/shelf")
	@PreAuthorize("@ato.hasAuthority('mall:goodsspu:edit')")
	public R shelf(@RequestParam(value = "shelf") String shelf, @RequestParam(value = "ids") String ids){
		//上架时判断是否有已下架的供应商商品，有则不让上架
		if(CommonConstants.YES.equals(shelf)){
			List<String> listSupplierSpuId = goodsSpuService.list(Wrappers.<GoodsSpu>query().lambda()
					.isNotNull(GoodsSpu::getSupplierId)
					.in(GoodsSpu::getId, ids)).stream().map(GoodsSpu::getSupplierSpuId).collect(Collectors.toList());
			long i = supplierGoodsSpuService.count(Wrappers.<SupplierGoodsSpu>query().lambda()
					.eq(SupplierGoodsSpu::getShelf, CommonConstants.NO)
					.in(SupplierGoodsSpu::getId, listSupplierSpuId));
			if(i > 0){
				return R.failed("选中的商品中有供应商商品已下架");
			}
		}
		goodsSpuService.shelf(shelf, ids);
		return R.ok();
	}

    /**
    * 通过id删除spu商品
    * @param id
    * @return R
    */
	@Operation(summary = "通过id删除spu商品")
    @SysLog("删除spu商品")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('mall:goodsspu:del')")
    public R removeById(@PathVariable String id){
		//在删除商品的时候加上判断，如该商品有参与营销活动就不能删除
		//砍价
		BargainInfo bargainInfo = new BargainInfo();
		bargainInfo.setSpuId(id);
		List<BargainInfo> listBargainInfo = bargainInfoService.list(Wrappers.query(bargainInfo));
		if(listBargainInfo != null && listBargainInfo.size() > 0){
			return R.failed("该商品有参与砍价活动，不能删除");
		}
		//拼团
		GrouponInfo grouponInfo = new GrouponInfo();
		grouponInfo.setSpuId(id);
		List<GrouponInfo> listGrouponInfo = grouponInfoService.list(Wrappers.query(grouponInfo));
		if(listGrouponInfo != null && listGrouponInfo.size() > 0){
			return R.failed("该商品有参与拼团活动，不能删除");
		}
		//秒杀
		SeckillInfo seckillInfo = new SeckillInfo();
		seckillInfo.setSpuId(id);
		List<SeckillInfo> listSeckillInfo = seckillInfoService.list(Wrappers.query(seckillInfo));
		if(listSeckillInfo != null && listSeckillInfo.size() > 0){
			return R.failed("该商品有参与秒杀活动，不能删除");
		}
        return R.ok(goodsSpuService.removeById(id));
    }

	/**
	 * 商品审核
	 * @param verifyStatus
	 * @param ids
	 * @return R
	 */
	@Operation(summary = "商品审核")
	@SysLog("商品审核")
	@PutMapping("/verify")
	@PreAuthorize("@ato.hasAuthority('mall:goodsspu:verify')")
	public R verify(@RequestParam(value = "verifyStatus") String verifyStatus, @RequestParam(value = "verifyDetail",required=false) String verifyDetail, @RequestParam(value = "ids") String ids){
		goodsSpuService.verify(verifyStatus, verifyDetail, ids);
		return R.ok();
	}

	/**
	 * 查询统计
	 * @param goodsSpu
	 * @return
	 */
	@Operation(summary = "查询统计")
	@GetMapping("/statistics")
	@PreAuthorize("@ato.hasAuthority('mall:goodsspu:statistics')")
	public R getStatistics(GoodsSpu goodsSpu) {
		if(StrUtil.isNotBlank(SecurityUtils.getUser().getShopId())){
			goodsSpu.setShopId(SecurityUtils.getUser().getShopId());
		}
		//总数量
		long countTotal = goodsSpuService.count(Wrappers.query(goodsSpu));
		//今天数量
		LocalDate localDate = LocalDateTime.now().toLocalDate();
		long countToday = goodsSpuService.count(Wrappers.query(goodsSpu).between("create_time", LocalDateTime.of(localDate, LocalTime.MIN), LocalDateTime.of(localDate, LocalTime.MAX)));
		Map<String, Object> rs = new HashMap<>();
		rs.put("countTotal",countTotal);
		rs.put("countToday",countToday);
		return R.ok(rs);
	}

	/**
	 * 初始化ES商品
	 * @return R
	 */
	@Operation(summary = "初始化ES商品")
	@SysLog("初始化ES商品")
	@PostMapping("/esinit")
	@PreAuthorize("@ato.hasAuthority('mall:goodsspu:esinit')")
	public R esInit() {
		goodsSpuService.esInit(goodsSpuService.getEsSpuIndexName());
		return R.ok();
	}

	/**
	 * 初始化ES商品（服务间调用）
	 * @return R
	 */
	@Operation(summary = "初始化ES商品（服务间调用）")
	@PostMapping("/esinit/{tenantId}")
	@Inside
	public R esInitInside(@PathVariable String tenantId) {
		goodsSpuService.esInit(StrUtil.format("{}_{}", "goods_spu", tenantId));
		return R.ok();
	}

	/**
	 * list查询通过ids
	 * @param ids ids
	 * @return
	 */
	@Operation(summary = "list查询通过ids")
	@PostMapping("/listbyids")
	public R getGoodsSpuListByIds(@RequestBody List<String> ids) {
		return R.ok(
				goodsSpuService.list(Wrappers.<GoodsSpu>query().lambda()
						.select(GoodsSpu.class, info -> !info.getColumn().equals("description"))
						.in(GoodsSpu::getId, ids))
		);
	}
}
